package api

import (
	"bbs-go/internal/controllers/render"

	"github.com/dchest/captcha"
	"github.com/kataras/iris/v12"
	"github.com/mlogclub/simple/web"

	"bbs-go/internal/pkg/config"
	"bbs-go/internal/pkg/errs"
	"bbs-go/internal/services"
)

type LoginController struct {
	Ctx iris.Context
}

// 注册
func (c *LoginController) PostSignup() *web.JsonResult {
	var (
		captchaId   = c.Ctx.PostValueTrim("captchaId")
		captchaCode = c.Ctx.PostValueTrim("captchaCode")
		email       = c.Ctx.PostValueTrim("email")
		phone       = c.Ctx.PostValueTrim("phone")
		username    = c.Ctx.PostValueTrim("username")
		password    = c.Ctx.PostValueTrim("password")
		rePassword  = c.Ctx.PostValueTrim("rePassword")
		nickname    = c.Ctx.PostValueTrim("nickname")
		redirect    = c.Ctx.FormValue("redirect")
	)

	departmentId, err := c.Ctx.PostValueInt("departmentId")
	if err != nil {
		return web.JsonErrorMsg("部门参数错误，请重新选择")
	}
	loginMethod := services.SysConfigService.GetLoginMethod()
	if !loginMethod.Password {
		return web.JsonErrorMsg("账号密码登录/注册已禁用")
	}

	if departmentId <= 0 {
		return web.JsonErrorMsg("请选择部门")
	}

	if len(nickname) == 0 {
		return web.JsonErrorMsg("昵称不能为空")
	}

	if len(email) == 0 {
		return web.JsonErrorMsg("邮箱不能为空")
	}

	if len(phone) == 0 {
		return web.JsonErrorMsg("手机号不能为空")
	}

	if !captcha.VerifyString(captchaId, captchaCode) {
		return web.JsonError(errs.CaptchaError)
	}

	user, err := services.UserService.SignUp(username, email, nickname, password, rePassword, phone, departmentId)
	if err != nil {
		return web.JsonError(err)
	}
	return render.BuildLoginSuccess(c.Ctx, user, redirect)
	// if user.Status == constants.StatusOk {
	// 	return render.BuildLoginSuccess(c.Ctx, user, redirect)
	// }
	// return web.Json(0, "注册成功，请等待审核", nil, true)
}

// 用户名密码登录
func (c *LoginController) PostSignin() *web.JsonResult {
	var (
		captchaId   = c.Ctx.PostValueTrim("captchaId")
		captchaCode = c.Ctx.PostValueTrim("captchaCode")
		username    = c.Ctx.PostValueTrim("username")
		password    = c.Ctx.PostValueTrim("password")
		redirect    = c.Ctx.FormValue("redirect")
	)
	loginMethod := services.SysConfigService.GetLoginMethod()
	if !loginMethod.Password {
		return web.JsonErrorMsg("账号密码登录/注册已禁用")
	}

	if config.Instance.IsProd() {
		if !captcha.VerifyString(captchaId, captchaCode) {
			return web.JsonError(errs.CaptchaError)
		}
	}
	user, err := services.UserService.SignIn(username, password)
	if err != nil {
		return web.JsonError(err)
	}
	return render.BuildLoginSuccess(c.Ctx, user, redirect)
}

// 退出登录
func (c *LoginController) GetSignout() *web.JsonResult {
	err := services.UserTokenService.Signout(c.Ctx)
	if err != nil {
		return web.JsonError(err)
	}
	return web.JsonSuccess()
}
